<template>
  <div class="full-page">
    <h1 class="auth-title">登录</h1>
    <van-form @submit="onSubmit" class="auth-form">
      <van-field autocomplete="off" v-model="username" name="username" label="用户名:" placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field autocomplete="off" v-model="password" type="password" name="password" label="密码:" placeholder="请输入密码"
        :rules="[{ required: true, pattern, message: getpsdMessage }]" />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>

    <router-link class="link" replace to="/register">没有账号，前往注册&gt;&gt;
    </router-link>
  </div>
</template>

<script>
import { Form, Field, Button, Toast } from "vant";
import axios from "axios";
export default {
  name: "login-page",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
  },
  data() {
    return {
      username: "",
      password: "",
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,12}$/,
    };
  },
  methods: {
    // 获取密码输入框输入出错的提醒文字
    getpsdMessage(value, rule) {
      if (value) {
        return "至少包含字母、数字，6-12位";
      } else {
        return "请填写密码";
      }
    },
    // 提交
    async onSubmit() {
      try {
        const res = await axios.post("/api/user/login", {
          username: this.username,
          password: this.password,
        });
        console.log(res);
        Toast("登录成功");
        // console.log(res.data.token);
        // 1.保存登录成功的token
        localStorage.setItem("token", res.data.token);

        // 2..修改登录状态
        this.$store.commit("user/setIsLogin", true);

        // 3..进入首页
        this.$router.replace("/");
      } catch (error) {
        console.log(error);
        Toast(error.response.data.msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@function vw($px) {
  @return ($px/375) * 100vw;
}

.full-page {
  background-image: url(https://img2.baidu.com/it/u=3312381130,3131391739&fm=253&fmt=auto&app=138&f=JPEG?);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%;
}

.van-cell {
  background: transparent;
  border-bottom: vw(1) solid #ccc;
}

.auth-title {
  font-weight: 700;
  text-align: center;
  font-size: vw(30);
  margin-top: vw(80);
  margin-bottom: 0;
}

.auth-form {
  margin: 0 auto;
  padding: vw(28);
}

.link {
  color: #2ec7c9;
  font-weight: 700;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: vw(10);
}
</style>
